package db

import (
	"fmt"
	"ginApi/config"
	"ginApi/model"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"github.com/pelletier/go-toml"
	"time"
)

var DB *gorm.DB

func Database() {
	driver := config.Conf.Get("database.driver").(string)
	c := config.Conf.Get(driver).(*toml.Tree)

	sourceName := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",
		c.Get("username").(string),
		c.Get("password").(string),
		c.Get("host").(string),
		c.Get("port").(int64),
		c.Get("database").(string))

	db, err := gorm.Open("mysql", sourceName)
	if err != nil {
		panic("db NewEngine error " + err.Error())
	}

	db.LogMode(true)

	//设置连接池
	//空闲
	db.DB().SetMaxIdleConns(20)
	//打开
	db.DB().SetMaxOpenConns(100)
	//超时
	db.DB().SetConnMaxLifetime(time.Second * 30)

	DB = db

	// 自动迁移模式
	db.AutoMigrate(&model.User{}, &model.Token{})
}